/**
 *
 *
 * @author TOTORO
 * @date 2021/7/13 14:07
 */
var $deleteProduct = jQuery;
$(function () {


    // 文档加载完成，加载所有店铺的优惠券
    $(document).ready(function () {
        // 获取所有的店铺
        var $shops = $(".J_Order");
        for (let i = 0; i < $shops.length; i++) {
            var sid = $shops.eq(i).attr("data-sid");
            // 计算店铺商品的总价
            var allPrice = 0;
            var count = 0;
            var $productItems = $shops.eq(i).find(".order-content");
            $productItems.each(function (index, el) {
                var amout = $(this).find(".td-price .J_Price").attr("data-spm-pe");
                var count = $(this).find(".td-amount .J_ItemAmount").val();
                var that = $(this);
                $.post("/shopCoupon_logic/useShopCoupon.htm", {"shopId":sid, "allPrice": amout}, function (data) {
                    console.table(data);
                    if(data!="no"){
                        couponJson = eval("("+ data +")");
                        var couponMoney = couponJson['couponMoney'];
                        var couponTitle = couponJson['couponTitle'];
                        var $nowPrice = that.find(".td-price .J_Price");
                        var discountPrice = parseFloat($nowPrice.attr("data-spm-pe")) - parseFloat(couponMoney);
                        var amout = that.find(".td-amount .J_ItemAmount").val();
                        var $sum = that.find(".td-sum .J_ItemSum");
                        that.find(".td-price .J_Price").text("￥"+discountPrice+".0").attr("data-spm-pe",discountPrice+".0");
                        $sum.text("￥"+parseInt(amout) * discountPrice +".0");

                        var $preferentialTips =  $("<div class='bundle-hd'>" +
                            "<div class='td-chk'></div>" +
                            "<div class='bd-title'>普通商品<i class='icon-bd-title'></i>" +
                            "</div>" +
                            "<div class='bd-promos'>" +
                            "<div class='act-promo'>" +
                            "<div class='act-promo-wrapper'>" +
                            "<ul class='act-promo-hint J_ScrollingPromoHint'>" +
                            "<li data-spm-anchor-id='a1z0d.6639537.1997196601.i3.42fa7484SdN6LE'>"+couponTitle+"</li>" +
                            "</ul>" +
                            "</div>" +
                            "</div>" +
                            "</div>" +
                            "</div>");
                        that.find(".item-holder").before($preferentialTips);
                        // 如果没有优惠券，删除下划线的原价
                    } else{
                        that.find(".td-price .price-original").remove();
                    }
                });
            });
        }
    })



    // 悬浮购物车某个商品sku属性上，触发修改按钮
    $(".item-props").hover(function () {
        var that = $(this);
        setTimeout(function () {
            that.addClass("item-props-can-hover");
        }, 300);
    }, function () {
        var that = $(this);
        setTimeout(function () {
            that.removeClass("item-props-can-hover");
        }, 300);
    });


    // 复选框选中操作
layui.use(['layer', 'form'], function(){
    var form = layui.form;

        // 选中商品的复选框
        form.on('checkbox(product-ck)', function (data) {
            var that = $(data.elem); //得到checkbox原始DOM对象
            var $parentItem = that.parents(".item-content");
            var flag = data.elem.checked; //是否被选中，true或者false
            if(flag) {
                // 如果该商品对应店铺下的商品都选中了，设店铺为已选择
                var $nowAllProduct = $(this).parents(".J_Order").find(".order-content");
                var isAllChecked = true;
                for (let i = 0; i < $nowAllProduct.length; i++) {
                    var checkedStatus = $nowAllProduct.eq(i).find("input:checkbox").prop("checked");
                    if(!checkedStatus){
                        isAllChecked = false;
                    }
                }
                // 如果完全选中
                if(isAllChecked){
                    $(this).parents(".J_Order").find(".shop-info input:checkbox").prop("checked", true);
                }
            } else{
                // 设该商品对应店铺的复选框为未选择
                $(this).parents(".J_Order").find(".shop-info input:checkbox").prop("checked", false);
            }
            form.render();
            updateAllChecked();
        });

        // 选中店铺的复选框
        form.on('checkbox(shop-ck)', function (data) {
            var that = $(data.elem); //得到checkbox原始DOM对象
            var $parentItem = that.parents(".J_Order");
            var $productItems = $parentItem.find(".order-content");
            var flag = data.elem.checked; //是否被选中，true或者false
            if(flag){
                $productItems.each(function (index, el) {
                    $(this).find("input:checkbox").prop("checked", true);
                })
            } else{
                $productItems.each(function (index, el) {
                    $(this).find("input:checkbox").prop("checked", false);
                })
            }
            form.render();
            updateAllChecked();

        });


    // 全选
    form.on('checkbox(all-ck)', function (data) {
        var that = $(data.elem); //得到checkbox原始DOM对象
        var $parentItem = that.parents("#J_Cart");
        // 获取旗下的所有商品和所有店铺
        var $productItems = $parentItem.find(".order-content");
        var $shopItems = $parentItem.find(".J_ItemHead");
        var flag = data.elem.checked; //是否被选中，true或者false
        if(flag){
            // 先循环店铺的
            $shopItems.each(function (index, el) {
                $(this).find("input:checkbox").prop("checked", true);
            });

            // 商品选中
            $productItems.each(function (index, el) {
                $(this).find("input:checkbox").prop("checked", true);
            });
        } else{
            $shopItems.each(function (index, el) {
                $(this).find("input:checkbox").prop("checked", false);
            });

            $productItems.each(function (index, el) {
                $(this).find("input:checkbox").prop("checked", false);
            });

        }
        form.render();
        updateAllChecked();
    });
    });



    // 单个移入收藏夹
    $(".move-collect").click(function () {
        var _this = $(this);
        var $x = $(this).offset().left;
        var $y = $(this).offset().top;
        $(".fav-box").show().css("top",$y+"px").css("left",$x+"px");
        // 移入收藏夹
        var ctId = $(this).parents(".order-content").attr("data-spm-ctid");
        var ctIds = new Array(ctId);
        $.post("/cart_logic/moveInCollect.htm", {"cartIds": ctIds}, function () {
            setTimeout(function () {
                var $thatShops = _this.parents(".J_OrderHolder");
                var productCount = $thatShops.find(".order-content").length;
                if(productCount <= 1) {
                    $thatShops.remove();
                } else{
                    _this.parents(".order-content").remove();
                }
                updateAllChecked();
                $(".fav-box").hide();
            }, 400);
        })
    });

    // 批量移入收藏夹
    $(".J_BatchFav").click(function () {
        // 获取所有选中商品的购物车id
        var selectedProduct =  $("#J_OrderList .order-content input[type='checkbox']:checked");
        if(selectedProduct.length < 1){
            layui.use('layer', function() {
                var layer = layui.layer;
                layer.msg("请先选择你要移至收藏夹的宝贝", {offset: "200px"});
                return false;
            });
        }

        setTimeout(function () {
            var cartIds = new Array();
            selectedProduct.each(function () {
                cartIds.push(parseInt($(this).parents(".order-content").attr("data-spm-ctid")));
                // 如果这个商品是店铺下最后一个商品，则整个删除，否则只删除商品行 （先获取店铺，再查找商品的长度）
                var $thatShops = $(this).parents(".J_OrderHolder");
                var productCount = $thatShops.find(".order-content").length;
                if(productCount <= 1) {
                    $thatShops.remove();
                } else{
                    $(this).parents(".order-content").remove();
                }
            });
            // 执行
            $.post("/cart_logic/moveInCollect.htm", {"cartIds": cartIds});
        }, 300);

    })

    // 点击从购物车删除某个商品,弹出确认框
    $(".J_Del").click(function () {
        $deleteProduct = $(this).parents(".order-content");
        var $deleteTip = generateDeleteTip(1).appendTo("body"); // 弹出确认框
        $deleteTip.show(400);
        $(".ks-overlay-mask").show();
    });

    // 点击确认单个删除
    $("body").on("click", ".oneDelete", function () {
        $.post("/cart_logic/deleteCartProduct.htm", {"cartId": $deleteProduct.attr("data-spm-ctid")});
        // 生成撤销本次删除提示
        var $revokeTip = $("<div id='J_Undo' class='undo-wrapper'>\n" +
            "<div class='undo-msg J_UndoMaxMsg'>\n" +
            "<p>成功删除 <em>1</em> 件宝贝，如有误，可<a href='/cart_logic/revokeDelete.htm?ttr="+Totoro.getConfusionRandom(30)+"' class='J_UndoDel'>撤销本次删除</a></p>\n" +
            "</div>\n" +
            "</div>");
        $deleteProduct.parents(".J_OrderHolder").before($revokeTip);

        // 如果这个商品是店铺下最后一个商品，则整个删除，否则只删除商品行 （先获取店铺，再查找商品的长度）
        var $thatShops = $deleteProduct.parents(".J_OrderHolder");
        var productCount = $thatShops.find(".order-content").length;
        if(productCount <= 1) {
            $thatShops.remove();
        } else{
            $deleteProduct.remove();
        }
        updateAllChecked();
        $("#ks-component500").hide(400);
        $(".ks-overlay-mask").hide();
        setTimeout(function () {
            $("#ks-component500").remove();
        }, 400);
    });

    // 点击批量删除按钮
    $(".J_DeleteSelected").click(function () {
        // 判断用户是否选中商品
       var selectedLength =  $("#J_OrderList .order-content input[type='checkbox']:checked").length;
        layui.use('layer', function(){
            var layer = layui.layer;
            // 如果未选中
            if(selectedLength<1){
                layer.msg('请先选中你需要删除的商品', {offset:'200px'});
                return false;
            }
            var $deleteTip = generateDeleteTip(2).appendTo("body"); // 弹出确认框
            $deleteTip.show(400);
            $(".ks-overlay-mask").show();
        });
    });

    // 确认批量删
    $("body").on("click", ".batchDelete", function () {
        // 获取所有选中商品的购物车id
        var selectedProduct =  $("#J_OrderList .order-content input[type='checkbox']:checked");
        // 生成撤销提示
        var $revokeTip = $("<div id='J_Undo' class='undo-wrapper'>\n" +
            "<div class='undo-msg J_UndoMaxMsg'>\n" +
            "<p>成功删除 <em>"+selectedProduct.length+"</em> 件宝贝，如有误，可<a href='/cart_logic/batchRevokeDelete.htm?ttr="+Totoro.getConfusionRandom(30)+"' class='J_UndoDel'>撤销本次删除</a></p>\n" +
            "</div>\n" +
            "</div>");
        selectedProduct.eq(0).parents(".J_OrderHolder").before($revokeTip);

        var cartIds = new Array();
        selectedProduct.each(function () {
            cartIds.push(parseInt($(this).parents(".order-content").attr("data-spm-ctid")));
            // 如果这个商品是店铺下最后一个商品，则整个删除，否则只删除商品行 （先获取店铺，再查找商品的长度）
            var $thatShops = $(this).parents(".J_OrderHolder");
            var productCount = $thatShops.find(".order-content").length;
            if(productCount <= 1) {
                $thatShops.remove();
            } else{
                $(this).parents(".order-content").remove();
            }
        });
        $.post("/cart_logic/batchDeleteCartProduct.htm", {"cartIds": cartIds});
        updateAllChecked();
        $("#ks-component500").hide(400);
        $(".ks-overlay-mask").hide();
        setTimeout(function () {
            $("#ks-component500").remove();
        }, 400);
    });


    // 点击关闭删除确认框
    $("body").on("click", ".J_DialogCancelBtn, .ks-dialog-close", function () {
        $("#ks-component500").hide(400);
        $(".ks-overlay-mask").hide();
        setTimeout(function () {
            $("#ks-component500").remove();
        }, 400);
    });


    // 点击结算
    $("#J_Go").click(function () {
        // 判断用户是否选择了商品
        var selectedLength =  $("#J_OrderList .order-content input[type='checkbox']:checked").length;
        if(selectedLength < 1){
            return false;
        }

        var sids = new Array();

        // 获得所有选中的商品
        var $allProduct = $("input:checkbox:checked[lay-filter='product-ck']");
        // 获得这些商品对应的店铺，实现去重功能
        for (let i = 0; i < $allProduct.length; i++) {
            var sid = $allProduct.eq(i).parents(".J_Order").attr("data-sid");
            sids.push(sid);
        }
        sids = Array.from(new Set(sids));
        var jsObject = new Array();
        // 使用js对象
        for (let i = 0; i < sids.length; i++) {
            var pids = new Array();
            var skuIds = new Array();
            var stocks = new Array();
            for (let j = 0; j < $allProduct.length; j++) {
                var sid = $allProduct.eq(j).parents(".J_Order").attr("data-sid");
                var pid = $allProduct.eq(j).parents(".order-content").attr("data-pid");
                var stock = $allProduct.eq(j).parents(".item-content").find(".td-amount .J_ItemAmount").val();
                var skuid = $allProduct.eq(j).parents(".item-content").find(".td-info").attr("data-skuid");
                if(sids[i] == sid){
                    pids.push(pid);
                    stocks.push(stock);
                    skuIds.push(skuid);
                }
            }
            jsObject.push({"sid":sids[i], "pids":pids, "stocks":stocks, "skuIds":skuIds});

        }
        var finalData = JSON.stringify(jsObject);
        // 保存信息
        $.ajaxSettings.async = false;
        $.post("/order_logic/saveProductInfo.htm", {"data":finalData}, function (data) {
            var rd = Totoro.getConfusionRandom(20);
            // 跳转至订单支付页面
            window.location.href = "/order/confirm_order.htm?ttr="+rd+"1";
        });
    })

});

/**
 * 通过选中状态i修改价钱数量
 */
var settlementStatus = false;
function updateAllChecked() {
    var $checkedBox = $("#J_OrderList").find("input:checkbox");
    var isAllChecked = true;
    for (let i = 0; i < $checkedBox.length; i++) {
        var checkedStatus = $checkedBox.eq(i).prop("checked");
        if(!checkedStatus){
            isAllChecked = false;
            break;
        }
    }
    console.log(isAllChecked)
    $("input:checkbox[lay-filter='all-ck']").each(function () {
        $(this).prop("checked", isAllChecked);
    });

    // 总价与选中商品数量
    var $total = $("#J_Total");
    var $sum = $("#J_SelectedItemsCount");

    $total.text(0.00);
    $sum.text(0);
    if(isAllChecked){
        // 获得所有的商品
        $(".order-content").each(function () {
            var isFail = $(this).hasClass("order-fail");
            if(!isFail) {
                // 改变选框颜色
                $(this).find(".item-body").addClass("item-selected");
                var price = parseFloat($(this).find(".td-price .J_Price").attr("data-spm-pe"));
                var amout = parseInt($(this).find(".td-amount .J_ItemAmount").val());

                $total.text(parseInt($total.text()) + (price * amout));
                $sum.text(parseInt($sum.text()) + 1);
            }
        });
    } else{
        // 获取所有选中的商品
        $("#J_OrderList .order-content input:checkbox:checked").each(function () {
            // 改变选框颜色
            var price = parseFloat($(this).parents(".order-content").find(".td-price .J_Price").attr("data-spm-pe"));
            var amout = parseInt($(this).parents(".order-content").find(".td-amount .J_ItemAmount").val());

            $total.text(parseInt($total.text()) + (price * amout));
            $sum.text(parseInt($sum.text())+1);
        });
    }
    $("#J_OrderList .order-content input:checkbox").each(function () {
        var chekcedStatus = $(this).prop("checked");
        if(chekcedStatus) {
            // 改变选框颜色
            $(this).parents(".item-body").addClass("item-selected");
        } else{
            $(this).parents(".item-body").removeClass("item-selected");
        }
    })

    $total.text($total.text()+".00");
    if($("#J_OrderList .order-content input:checkbox:checked").length<1){
        $("#J_Go").addClass("submit-btn-disabled");
        settlementStatus = false;
    } else{
        $("#J_Go").removeClass("submit-btn-disabled");
        settlementStatus = true;
    }
    reloadForm();
}


function reloadForm() {
    layui.use(['layer', 'form'], function() {
        var form = layui.form;
        form.render();
    });
}







// ------------------- 以下为购物车SKU修改的处理部分 ------------------------
var isFirst = true;
var pid, skuId, cartId;
var $nowAttrInfo = jQuery;
$(function () {
    /**
     * 点击修改，展示属性修改面板
     */
    $("body").on("click", ".btn-edit-sku", function (){
        // 一、先渲染商品图片
        var imgSrc = $(this).parents(".item-content").find(".item-pic img").attr("src");
        // 变量指向当前选中的
        $nowAttrInfo = $(this).parents(".item-content");


        // 获取商品id和skuid - cartId
        pid = $(this).parents(".order-content").attr("data-pid");
        skuId = $(this).parents(".td-info").attr("data-skuid");
        cartId = $(this).parents(".order-content").attr("data-spm-ctid");

        var $x = $(this).offset().left;
        // 高度要根据最后一个sku属性决定
        var $y = $(this).prev().offset().top;
        // 生成修改框
        if($(".J_SkuEdit").length<1) {
            var $editBox = generateEditSku($x, $y, imgSrc, pid, skuId).appendTo("body");
        } else{
            return false;
        }
        $.ajax({
            type: "GET",
            url: "${pageContext.request.contextPath}/productBuy_logic/initSku.htm",
            data: {"pid": pid},
            async: false,
            success: function (data) {
                initCSku(data);
                change(pid, skuId, true, false, null);

                // 通过skuid拿到属性组，进行自动选择
                $.get("/productBuy_logic/getSkuAttr.htm", {"skuId":skuId}, function (data) {
                    var skuJson = eval("("+ data +")");
                    var skuValues = new Array();
                    for (var key in skuJson){
                        // 循环所有sku-li
                        skuValues.push(skuJson[key]);
                    }
                    skuValues.reverse();

                    var allSelect = $(".hidden-msg").prevAll();
                    for (let i = allSelect.length-1; i >= 0; i--) {
                        var cs = allSelect.eq(i).find("li");
                        for (let j = 0; j < cs.length; j++) {
                            if(cs.eq(j).find("span").text() == skuValues[i]){
                                cs.eq(j).addClass("selected").siblings().removeClass("selected");
                            }
                        }
                    }
                });

                // 每次初始化都会让最后一批属性失效，因为指定属性方法并不完美
                // 获取最后一批的上一批选中的skuid
                var prevSkuId = $(".J_Prop:last").prev().find(".selected").attr("data-skuid");
                $(".J_Prop:last li").each(function (index, el) {
                    $(this).attr("data-skuid", parseInt(prevSkuId)+index);
                });



            }
        });
    });


    // 点击sku具体属性按钮
    $("body").on("click", ".prop-block", function () {
        change(pid, $(this).attr("data-skuid"), false, true, $(this));
    });


    /**
     * 点击确定，修改sku
     */
    $("body").on("click", ".J_AddCart", function () {
        // 判断用户是否全选中属性
        var isComplete = true;
        var $props = $(".J_Prop");
        for (let i = 0; i < $props.length; i++) {
            if($props.eq(i).find(".selected").length<1){
                $(".hidden-msg").show();
                isComplete = false;
            }
        }
        if(!isComplete){
            return false;
        }


        // 获取新选中的skuId
        var $selectedEl = $(".hidden-msg").prev().find(".selected");
        // 如果选中的skuid 和 开始的skuid相同，则直接消失
        if($selectedEl.attr("data-skuid") == skuId) {
            var $tips = generateSamePanel("您修改后的购买信息和修改前一致").appendTo($("body"));
            $tips.show(400);
            $(".ks-overlay-mask").show();
            return false;
        }
        $.post("/cart_logic/updateCpAttr.htm", {"cartId":cartId,"skuId":$selectedEl.attr("data-skuid")}, function (data) {
            if(data == "no"){
                // 与库同时删除
                $(".sku-edit-popup").remove();
                $nowAttrInfo.parents(".order-content").remove();
                var $tips = generateSamePanel("该商品已经存在您的购物车，以为您进行整合操作！").appendTo($("body"));
                $tips.show(400);
                $(".ks-overlay-mask").show();
                return false;
            }
            var dataJson = eval("("+ data +")")
            var skuId = dataJson['id'];
            var skuData = eval("("+ dataJson['productSpaceData'] +")");
            var skuPrice = dataJson['productPrice'];
            var skuStock = dataJson['productStock'];

            // 获取所有的键
            var skuKeys = new Array();
            for (var key in skuData){
                skuKeys.push(key);
            }

            // 修改该商品的展示属性
            $nowAttrInfo.find(".td-info").attr("data-skuid", skuId);
            for (let i = 0; i < skuKeys.length; i++) {
                $nowAttrInfo.find(".td-info .item-props").children(":eq("+i+")").text(skuKeys[i]+":"+skuData[skuKeys[i]].toString().split("|")[0]);
            }
            // 修改商品价格
            $nowAttrInfo.find(".td-price .J_Price").text("￥"+skuPrice+".0");
            $nowAttrInfo.find(".td-price .J_Price").attr("data-spm-pe", skuPrice);
            // 修改单商品总金额
            var productCount = $nowAttrInfo.find(".td-amount .J_ItemAmount").val();
            $nowAttrInfo.find(".td-sum .J_ItemSum").text("￥"+(skuPrice * parseInt(productCount))+".0");
            $(".sku-edit-popup").remove();
        })
    });

    /**
     * 点击取消选择，关闭sku编辑面板
     */
    $("body").on("click", ".J_Cancel", function () {
        $(".sku-edit-popup").remove();
    });


    // 点击关闭sku提示面板
    $("body").on("click", "#ks-overlay-close-ks-component5005", function () {
        $("#ks-component5005").hide(400);
        $(".ks-overlay-mask").hide();
        setTimeout(function () {
            $("#ks-component5005").remove();
        }, 400)
    });


    // 以下为 修改商品数量 --------------------------
    // 1、通过按钮减少商品
    $(".J_Minus").click(function () {
        var $pt = $(this).parents(".item-content");
        var nowPe = $pt.find(".td-price .J_Price").attr("data-spm-pe");
        var $v = $(this).next();
        if($v.val() > 1){
            $v.val(parseInt($v.val())-1);
            $pt.find(".td-sum .J_ItemSum").text("￥"+parseInt(nowPe) * parseInt($v.val())+".0");
            $(this).next().next().removeClass("no-plus");
        }
        // 让按钮便灰色
        if($v.val() <=1){
            $(this).addClass("no-minus");
        } else{
            $(this).removeClass("no-minus");
        }
        $.post("/cart_logic/updateCpAttr.htm", {"cartId":$(this).parents(".order-content").attr("data-spm-ctid"), "count":$v.val()});
        updateAllChecked();
    });

    // 通过输入框控修改商品数量
    $(".J_ItemAmount").keyup(function () {
        var $pt = $(this).parents(".item-content");
        var maxSk = parseInt($pt.find(".td-info").attr("data-spm-sk"));
        var nowPe = $pt.find(".td-price .J_Price").attr("data-spm-pe");
        if($(this).val() > maxSk){
            $(this).val(maxSk);
            $(this).next().addClass("no-plus");
            $(this).prev().removeClass("no-minus");
        }
        if($(this).val() < 1){
            $(this).val(1);
            $(this).prev().addClass("no-minus");
            $(this).next().removeClass("no-plus");
        }
        $pt.find(".td-sum .J_ItemSum").text("￥"+parseInt(nowPe) * parseInt($(this).val())+".0");
        $.post("/cart_logic/updateCpAttr.htm", {"cartId":$(this).parents(".order-content").attr("data-spm-ctid"), "count":$(this).val()});
        updateAllChecked();
    })

    // 2、通过按钮增加商品
    $(".J_Plus").click(function () {
        var $pt = $(this).parents(".item-content");
        var nowPe = $pt.find(".td-price .J_Price").attr("data-spm-pe");
        var $v = $(this).prev();
        var maxSk = parseInt($pt.find(".td-info").attr("data-spm-sk"));
        if($v.val() < maxSk){
            $v.val(parseInt($v.val())+1);
            $pt.find(".td-sum .J_ItemSum").text("￥"+parseInt(nowPe) * parseInt($v.val())+".0");
            $(this).prev().prev().removeClass("no-minus");
        }

        // 让按钮变色
        if($v.val() <= maxSk){
            $(this).removeClass("no-plus");
        } else{
            $(this).addClass("no-plus");
        }
        $.post("/cart_logic/updateCpAttr.htm", {"cartId":$(this).parents(".order-content").attr("data-spm-ctid"), "count":$v.val()});
        updateAllChecked();
    });

});

/**
 * 初始化第一次的Sku属性
 * @param data
 */
function initCSku(data) {
    // 分割字符
    var params = data.split("<>");
    // 获取商品sku属性
    var skus = params[0];
    var skuJson = eval("(" + skus +")");
    var allCategory = skuJson[0]['productSpaceData'].replace("{", "").replace("}", "").replaceAll("\"", "").split(",");
    var skuData = new Array();
    for (let i = 0; i < skuJson.length; i++) {
        skuData.push(eval("("+ skuJson[i]['productSpaceData'] +")"));
    }
    var skuStock = new Array();
    for (let i = 0; i < skuJson.length; i++) {
        skuStock.push(eval("("+ skuJson[i]['productStock'] +")"))
    }
    // 获取sku组编号
    var skuCodes = params[1].split(",");
    // 先获取所有的键
    var skuKeys = new Array();
    for (let i = 0; i < allCategory.length; i++) {
        skuKeys.push(allCategory[i].split(":")[0])
    }

    var skuBoxs = new Array();
    for (let i = 0; i < 1; i++) {
        var $skuBox = generateSkuBox(skuKeys[i], i);
        skuBoxs.push($skuBox);
        $(".hidden-msg").before($skuBox);
    }
    var helpArray = new Array();
    for (let i = 0; i < 1; i++) {
        for (let j = 0; j < skuData.length; j++) {
            if(j>0){
                helpArray.push(skuData[j-1][skuKeys[i]]);
            }
            if(!helpArray.includes(skuData[j][skuKeys[i]])){
                if(j == 0){
                    var skuLi = generateCkb(skuData[j][skuKeys[i]], skuCodes[j]).appendTo(skuBoxs[i].find("ul"));
                } else{
                    var skuLi = generateB(skuData[j][skuKeys[i]], skuCodes[j]).appendTo(skuBoxs[i].find("ul"));
                }
            }
        }
    }
}

/**
 * 改变选中状态，更换sku属性组
 * @param pid
 * @param skuId
 * @param isInit
 * @param isThat
 * @param that
 * @returns {boolean}
 */
function change(pid, skuId, isInit, isThat, that){
    var cs = $("li[data-skuid="+skuId+"]");
    var cs2 = cs.parents(".prop");
    cs2.nextAll("dl").remove();
    var that = isThat?that:$("li[data-skuid="+skuId+"]");
    var isSelected = that.hasClass("selected");
    if(isThat){
        if(isSelected && !isFirst){
            that.removeClass("selected");
            return false;
        }
        isFirst = false;
    }
    that.addClass("selected").siblings().removeClass("selected");
    var nowIndex = isInit?0:that.parents(".J_Prop").attr("data-index");
    $.ajaxSettings.async = false;
    $.get("/productBuy_logic/getSkuAttrs.htm", {"pid": pid, "skuId":skuId, "nowIndex": nowIndex}, function (data) {
        // 分割字符
        var params = data.split("<>");
        // 获取商品sku属性
        var skus = params[0];
        var skuJson = eval("(" + skus +")");
        var skuData = new Array();
        for (let i = 0; i < skuJson.length; i++) {
            skuData.push(eval("("+ skuJson[i]['productSpaceData'] +")"));
        }
        var allCategory = skuJson[0]['productSpaceData'].replace("{", "").replace("}", "").replaceAll("\"", "").split(",");
        // 获取sku组编号
        var skuCodes = params[1].split(",");
        // 先获取所有的键
        var skuKeys = new Array();
        for (let i = 0; i < allCategory.length; i++) {
            skuKeys.push(allCategory[i].split(":")[0])
        }
        // 库存
        var skuStock = new Array();
        for (let i = 0; i < skuJson.length; i++) {
            skuStock.push(eval("("+ skuJson[i]['productStock'] +")"))
        }
        console.log(skuStock)

        // 删除对应个数的键，因为点击的和点击之前的是保持不变的
        for (let i = 0; i <= nowIndex; i++) {
            skuKeys.shift();
        }

        // 删除当前点击的属性div之后的所有div
        for (let i = 0; i < skuKeys.length; i++) {
            $(".tm-sale-prop[data-index="+nowIndex+"]").next().remove();
        }

        var skuBoxs = new Array();
        for (let i = 0; i < skuKeys.length; i++) {
            var skuBox = generateSkuBox(skuKeys[i], parseInt(nowIndex)+(i+1));
            skuBoxs.push(skuBox);
            $(".hidden-msg").before(skuBox);
        }
        var helpArray = new Array();
        for (let i = 0; i < skuKeys.length; i++) {
            for (let j = 0; j < skuData.length; j++) {
                if(j>0){
                    helpArray.push(skuData[j-1][skuKeys[i]]);
                }
                if(!helpArray.includes(skuData[j][skuKeys[i]])){
                    if(j == 0){
                        var skuLi = generateCkb(skuData[j][skuKeys[i]], skuCodes[j]).appendTo(skuBoxs[i].find("ul"));
                    } else{
                        var skuLi = generateB(skuData[j][skuKeys[i]], skuCodes[j]).appendTo(skuBoxs[i].find("ul"));
                    }
                }
            }
        }

    });
}

function updateSku() {
    // 获取最后一个选中的skuid ，根据它改变价格库存
    var finalSkuId = $(".J_Prop:last .selected").attr("data-skuid");
    $.get("/productBuy_logic/getSkuData.htm", {"skuId":finalSkuId}, function (data) {
        var skuJson = eval("("+ data +")");
        var price = skuJson["productPrice"];
        var stock = skuJson["productStock"];
    });
}

function generateSkuBox(text, index) {
    return $("<dl class='prop clearfix J_Prop' data-index='"+index+"'>"+
        "<dt>"+text+"</dt>"+
        "<dd>"+
        "<ul class='clearfix'>"+
        "</ul>"+
        "</dd>"+
        "</dl>");
}

function generateCkb(text, skuId) {
    var graphic = text.toString().split("\|");
    var isHaveImg = graphic.length > 1;
    return $("<li data-prop='"+text+"' data-skuid='"+skuId+"' class='prop-block J_PropBlock selected "+ (isHaveImg?"img-mode":"") +"' title='"+ (isHaveImg?graphic[0]:text) +"'>"+
        "<a href='javascript: void(0)' "+ (isHaveImg?"style='background:url("+graphic[1]+") 50% 50% no-repeat;'":"") +"><span>"+(isHaveImg?"":graphic[0])+"</span></a><i></i></li>"+
        "</ul>");
}

function generateB(text, skuId) {
    var graphic = text.toString().split("\|");
    var isHaveImg = graphic.length > 1;
    return $("<li data-prop='"+text+"' data-skuid='"+skuId+"' class='prop-block J_PropBlock "+ (isHaveImg?"img-mode":"") +"' title='"+ (isHaveImg?graphic[0]:text) +"'>"+
        "<a href='javascript: void(0)' "+ (isHaveImg?"style='background:url("+graphic[1]+") 50% 50% no-repeat;'":"") +"><span>"+(isHaveImg?"":graphic[0])+"</span></a><i></i></li>"+
        "</ul>");
}

/**
 * 生成sku修改面板
 * @param x
 * @param y
 * @param imgSrc
 * @returns {*|Window.jQuery|HTMLElement}
 */
function generateEditSku(x, y, imgSrc, pid, skuId) {
    return $("<div class='J_SkuEdit sku-edit-popup' style='display: block; top: "+(parseInt(y)+24)+"px; left: "+(parseInt(x) -179)+"px;'>"+
        "<div class='sku-edit-content'>"+
        "<div class='sku-props-selector clearfix'>"+

        "<div class='msg hidden-msg' style='display: none;'>"+
        "<p class='error J_ErrorInfo'>请选择商品属性</p>"+
        "</div>"+
        "<p class='operate'>"+
        "<a href='javascript:void(0);' class='add-cart J_AddCart'>"+
        "<span>确定</span>"+
        "</a>"+
        "<a href='javascript:void(0);' class='cancel J_Cancel'>取消</a>"+
        "</p>"+
        "</div>"+
        "</div>"+
        "<div class='sku-item-pic J_SkuItemPic' style='height: 221px;'>"+
        "<div class='cart-pic s160'><a href='/buy.htm?pid="+pid+"&skuCode="+skuId+"' target='_blank'>"+
        "<img src='"+imgSrc+"'></a>"+
        "</div>"+
        "</div>"+
        "<span class='arrow'></span>"+
        "</div>");
}


/**
 * 生成修改前后一样的提示面板
 * @returns {*|Window.jQuery|HTMLElement}
 */
function generateSamePanel(text) {
    return $("<div id='ks-component5005' class='ks-dialog ks-overlay cart-dialog cart-dialog-alert' tabindex='0' role='dialog' aria-labelledby='ks-stdmod-header-ks-component5005' style='width: 374px; left: 761.5px; top: 412px; display: none' aria-hidden='false'>\n" +
        "<a href='javascript:void('close')' id='ks-overlay-close-ks-component5005' class='ks-dialog-close ks-overlay-close' role='button'>\n" +
        "    <span class='ks-dialog-close-x ks-overlay-close-x'>close</span>\n" +
        "</a>\n" +
        "<div id='ks-content-ks-component5005' class='ks-dialog-content ks-overlay-content'>\n" +
        "    <div class='ks-dialog-header ks-overlay-header' style='\n" +
        "' id='ks-stdmod-header-ks-component5005'>提示信息</div>\n" +
        "    <div class='ks-dialog-body ks-overlay-body' style='\n" +
        "' id='ks-stdmod-body-ks-component5005'>"+text+"</div>\n" +
        "    <div class='ks-dialog-footer ks-overlay-footer' style='\n" +
        "' id='ks-stdmod-footer-ks-component5005'><span class='cart-icon icon-warning'></span></div>\n" +
        "</div>\n" +
        "<div tabindex='0'></div></div>");
}


/**
 * 删除宝贝确定
 * @returns {*|Window.jQuery|HTMLElement}
 */
function generateDeleteTip(deleteType) {
    return $("<div id='ks-component500' class='ks-dialog ks-overlay cart-dialog cart-dialog-confirm' tabindex='0' role='dialog' aria-labelledby='ks-stdmod-header-ks-component500' style='width: 374px; left: 761.5px; top: 209px; display: none' aria-hidden='false'>\n" +
        "<a href='javascript:void('close')' id='ks-overlay-close-ks-component500' class='ks-dialog-close ks-overlay-close' role='button'>\n" +
        "    <span class='ks-dialog-close-x ks-overlay-close-x'>close</span>\n" +
        "</a>\n" +
        "<div id='ks-content-ks-component500' class='ks-dialog-content ks-overlay-content'>\n" +
        "    <div class='ks-dialog-header ks-overlay-header' style='\n" +
        "' id='ks-stdmod-header-ks-component500'>"+(deleteType==1?"宝贝删除":"宝贝批量删除")+"</div>\n" +
        "    <div class='ks-dialog-body ks-overlay-body' style='\n" +
        "' id='ks-stdmod-body-ks-component500'>"+(deleteType==1?"确认要删除该宝贝吗？":"确认要删除这些宝贝吗？")+"</div>\n" +
        "    <div class='ks-dialog-footer ks-overlay-footer' style='\n" +
        "' id='ks-stdmod-footer-ks-component500'><a href='javascript:void(0)' class='dialog-btn "+(deleteType==1?"oneDelete":"batchDelete")+"'>确&nbsp;定</a><a href='javascript:void(0)' class='dialog-btn dialog-cancel J_DialogCancelBtn'>关&nbsp;闭</a></div>\n" +
        "</div>\n" +
        "<div tabindex='0'></div></div>");
}
